package nl.zoidberg.calculon.opening;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.Logger;

import nl.zoidberg.calculon.model.Board;

import org.apache.commons.digester.Digester;

public class OpeningBook {
	private static Logger log = Logger.getLogger(OpeningBook.class.getName());
	private static OpeningBook defaultBook;

	private Map<String, List<String>> book = new HashMap<String, List<String>>();
	
	public static OpeningBook getDefaultBook() {
		if(defaultBook != null) {
			return defaultBook;
		}

		Digester digester = new Digester();
		digester.addObjectCreate("calculon/opening-lines", OpeningBook.class);
		digester.addCallMethod("calculon/opening-lines/line", "addMoveList", 0);

		try {
			log.fine("Creating opening book");
			defaultBook = (OpeningBook) digester.parse(OpeningBook.class.getResourceAsStream("/calculon.xml"));
			return defaultBook;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public void addMoveList(String s) {
		Board board = new Board().initialise();
		for(StringTokenizer st = new StringTokenizer(s); st.hasMoreTokens(); ) {
			String nextMove = st.nextToken();
			String boardId = board.getCacheId();
			List<String> moves = book.get(boardId);
			if(moves == null) {
				moves = new ArrayList<String>();
				book.put(boardId, moves);
			}
			if( ! moves.contains(nextMove)) {
				moves.add(nextMove);
			}
			board.applyPgnMove(nextMove);
		}
	}
	
	public String getBookMove(Board board) {
		if(board == null) {
			return null;
		}
		
		List<String> moves = book.get(board.getCacheId());
		if(moves == null) {
			return null;
		}
		return moves.get((int)(Math.random()*moves.size()));
	}
}
